export const BASE_URL = 'http://192.168.1.106:8080'
export const IGNORED_URL = ['/login', '/register']

function request(options = {}) {
    const {
        url,
        method = 'GET',
        data = {},
        header = {},
        responseType = 'json',
        timeout = 100000,
        filePath,
        name = 'file'
    } = options

    // 忽略路径判断
    const isIgnored = IGNORED_URL.some(i => url.startsWith(i))

    const token = uni.getStorageSync('token') || ''
    if (!isIgnored && token) header['Authorization'] = `Bearer ${token}`

    if (options.upload) {
        return new Promise((resolve, reject) => {
            uni.uploadFile({
                url: BASE_URL + url,
                filePath,
                name,
                formData: data,
                header,
                timeout,
                success: res => {
                    try {
                        const result = JSON.parse(res.data)
                        resolve(result)
                    } catch (e) {
                        resolve(res.data)
                    }
                },
                fail: reject
            })
        })
    }

    if (options.download) {
        return new Promise((resolve, reject) => {
            uni.downloadFile({
                url: BASE_URL + url,
                header,
                timeout,
                success: res => {
                    if (res.statusCode === 200) resolve(res.tempFilePath)
                    else reject(res)
                },
                fail: reject
            })
        })
    }

    // 普通请求
    return new Promise((resolve, reject) => {
        uni.request({
            url: BASE_URL + url,
            method: method.toUpperCase(),
            data,
            header,
            responseType,
            timeout,
            success: res => {
                if (res.statusCode === 401) {
                    uni.removeStorageSync('token')
                    uni.reLaunch({ url: '/pages/login/login' })
                    return
                }
                if (res.statusCode === 200) resolve(res.data)
                else reject(res)
            },
            fail: err => {
                console.log('网络异常：', err)
                reject(err)
            }
        })
    })
}

// 简写方法
['get', 'post', 'put', 'delete'].forEach(method => {
    request[method] = (url, data = {}, opt = {}) => {
        return request(Object.assign({ url, data, method }, opt))
    }
})

// 上传文件
request.upload = (url, filePath, data = {}, opt = {}) => {
    return request(Object.assign({ url, filePath, data, upload: true }, opt))
}

// 下载文件
request.download = (url, opt = {}) => {
    return request(Object.assign({ url, download: true }, opt))
}

export default request
